/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.MOS.javacc.applications;

import br.com.MOS.javacc.SDL.MOSSDLBackend;
import br.com.MOS.javacc.gui.GUILoader;
import br.com.MOS.mplayer.MPlayer;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Vector;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.microedition.xlet.Xlet;
import javax.microedition.xlet.XletStateChangeException;

/**
 *
 * @author Leonardo Baptista (cbs)
 */
public class ApplicationManager {

    private static Vector<Application> threads;
    private static boolean some_active = false;

    /**
     * @param args the command line arguments
     */
    public static void init() {
        threads = new Vector<Application>();
        loadGUIXlet();
    }

    public static void killXlets(String uuid){
        int i=0;
        while (i<threads.size()){
            if ( threads.get(i).context.getID().equals(uuid)){
                threads.remove(i);
            }
            i++;
        }
        if (threads.size() == 1){
            Application app =  (Application)threads.get(0);
            try {
                MOSSDLBackend.getInstance().clearScreen();
                app.xlet.startXlet();
            } catch (XletStateChangeException ex) {
                //Se deu pau fecha tudo!
                com.sun.dtv.lwuit.VirtualImplementation.PARAR_DE_RODAR = true;
            }
        }
        if (threads.size() == 0){
            System.out.println("Atencao: O MOS NUNCA DEVE PARAR DE EXECUTAR.\nUSE ISSO SOMENTE PARA TESTES.");
            com.sun.dtv.lwuit.VirtualImplementation.PARAR_DE_RODAR = true;
        }
    }

    public static void loadGUIXlet(){
        Xlet xlet = new GUILoader();
        ApplicationContext context = new ApplicationContext();
        Application app = new Application(xlet, context);
        app.setPriority(Thread.MIN_PRIORITY);
        threads.add(app);
        app.run();// .start();
    }

    public static void loadXlet(String p_jarFile){

        String mainClass = getMainClass(p_jarFile);
        if (mainClass == null)
        {
            System.out.println("JAR SEM MAIN CLASS;");
            return;
        }
        if (mainClass.equals("ERRO")){
            System.out.println("JAR SEM ARQUIVO MANIFEST;");
            return;
        }
        URL[] url = new URL[1];
        try {
            url[0] = new URL("file://" +p_jarFile);
        } catch (MalformedURLException ex) {
            Logger.getLogger(ApplicationManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        ClassLoader loader = new URLClassLoader(url);
        Class xx = null;
        Xlet xlet = null;
        try {
            xx = loader.loadClass( mainClass );
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ApplicationManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            xlet = (Xlet)xx.newInstance();
        } catch (InstantiationException ex) {
            Logger.getLogger(ApplicationManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(ApplicationManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        ApplicationContext context = new ApplicationContext();
        Application app = new Application(xlet, context);
        threads.add(app);
        app.start();
    }

    private static String getMainClass(String p_jarFile){
        JarFile jf = null;
        try {
            jf = new JarFile(p_jarFile);
        } catch (IOException ex) {
            Logger.getLogger(ApplicationManager.class.getName()).log(Level.SEVERE, null, ex);
            return "ERRO";
        }
        Manifest m= null;
        try {
            m = jf.getManifest();
        } catch (IOException ex) {
            Logger.getLogger(ApplicationManager.class.getName()).log(Level.SEVERE, null, ex);
            return "ERRO";
        }
        return m.getMainAttributes().getValue("Main-Class");
    }

}
